package icu.sehnen.es.service.impl;


import icu.sehnen.es.entity.ESUser;
import icu.sehnen.es.entity.User;
import icu.sehnen.es.reponsitory.ESUserRepository;
import icu.sehnen.es.service.ESUserService;
import org.elasticsearch.index.query.MatchAllQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.List;

import static org.elasticsearch.index.query.QueryBuilders.matchAllQuery;
import static org.elasticsearch.index.query.QueryBuilders.matchQuery;

/**
 * @author huangqing
 * @version 1.0
 * @date 2021/5/7 16:28
 */
@Service
public class ESUserServiceImpl implements ESUserService {
    @Autowired
    private ESUserRepository esPermissionRepository;
    @Autowired
    private ElasticsearchRestTemplate elasticsearchRestTemplate;
    @Override
    public Page<ESUser> search(String keyword, Integer pageNum, Integer pageSize) {
        PageRequest pageable = PageRequest.of(pageNum-1, pageSize);
        NativeSearchQuery username = new NativeSearchQueryBuilder()
                .withQuery(matchQuery("username", keyword))
                .withPageable(pageable)
                .build();
        Page<ESUser> search = esPermissionRepository.search(username);
        return search;
    }
    @Override
    public SearchHits searchHit(String keyword, Integer pageNum, Integer pageSize) {
        Query username = new NativeSearchQueryBuilder()
                .withQuery(matchQuery("username", keyword))
                .withHighlightFields(
                        new HighlightBuilder.Field("username").preTags("<font color=\"red\">").postTags("</font>")
                )
                .build();
        return elasticsearchRestTemplate.search(username, ESUser.class);
    }

    @Override
    public User save(User user) {
        return  elasticsearchRestTemplate.save(user);
    }

    @Override
    public Page<ESUser> findAll(Integer pageNum, Integer pageSize) {
        PageRequest pageable = PageRequest.of(pageNum-1, pageSize);
        NativeSearchQuery username = new NativeSearchQueryBuilder()
                .withQuery(matchAllQuery())
                .withPageable(pageable)
                .build();
        Page<ESUser> search = esPermissionRepository.search(username);
        return search;
    }

}